<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>canvas test</title>
  <style>
    body{
      text-align: center;
    }
    #cvs1{
      background-color: #cccccc;
    }
  </style>
</head>
<body>
  <h4>canvas矩形</h4>
  <!-- 创建画布 -->
  <canvas id="cvs1" width="500" height="400"></canvas>

  <script>
    var canvas = document.getElementById("cvs1");
    var ctx = canvas.getContext("2d");


    // 空心矩形样式
    ctx.strokeStyle = "#00f";
    // 空心矩形
    ctx.strokeRect(0,0,100,80);
    
    // 实心矩形样式
    ctx.fillStyle = "#f00";
    // 实心矩形
    ctx.fillRect(400,0,100,80);

    // 清空画布
    // ctx.clearRect(0,0,500,400);


    // 左右跑动的 矩形
    var x = 0;
    var xDirection = 1;
    var time = setInterval(()=>{
      if(x >= 400){
        xDirection = -1;
      }else if(x <= 0){
        xDirection = 1;
      }
      x += 5*xDirection;
      ctx.clearRect(0,100,500,400);
      ctx.fillRect(x,160,100,80);
    },50)

  </script>
</body>
</html>